<template>
  <div style="">
    <Header :left="true" leftText="返回" title="资源呼叫-物流"> </Header>
    <div class="textScroll">
      <Form>
        <Field v-model="form.equipName" ref="equipNameFocus" size="large" @keyup.enter.native="afterScan" center colon
          label="设备编码">
          <Icon slot="right-icon" center name="enlarge" size="2em" @click="showScanner"></Icon>
        </Field>
        <Field v-model="form.equipDesc" :readonly="true" size="large" center colon label="设备名称" />

        <Field v-model="form.user" :readonly="true" size="large" center colon label="呼叫人" />

        <Field v-model="form.callTime" :readonly="true" size="large" center colon label="呼叫时间" />

        <Field v-model="form.callReason" readonly clickable size="large" placeholder="请选择呼叫原因" center colon label="呼叫原因"
          right-icon="assets/right.png" @click="sourceShowPicker = true" />
        <van-popup v-model="sourceShowPicker" round position="bottom">
          <van-picker showPicker="false" title="呼叫原因选择" value-key="faultDesc" show-toolbar @confirm="sourceOnConfirm"
            :columns="columns" @cancel="sourceShowPicker = false" default-index="0" />
        </van-popup>
      </Form>

      <div class="container dwo">
        <div class="card_under">
          <NoticeBar color="#1989fa" background="#ecf9ff" left-icon="video">多媒体信息</NoticeBar>
          <Field v-model="form.remark" rows="1" autosize size="large" label="呼叫描述" type="textarea" maxlength="50"
            placeholder="请输入呼叫描述" show-word-limit />
          <Field size="large" :readonly="true" name="checkres" @click="showCamera" label="点击拍照上传"
            placeholder="————点击拍照————" right-icon="assets/right.png" />
          <div v-if="form.picList !== undefined && form.picList.length > 0">
            <div style="margin-left: 15px" v-for="(imgUrl, ks) in form.picList" :key="ks">
              <div class="van-uploader__wrapper" style="float: left">
                <div class="van-uploader__preview">
                  <div @click="picShow(ks)" class="van-image van-uploader__preview-image">
                    <img :src="imgUrl" class="van-image__img" />
                  </div>
                  <div class="van-uploader__preview-delete" @click="delObj('pic', imgUrl)">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <Field name="checkres" label="视频拍摄" size="large">
            <template #input>
              <Button class="mg5" icon="play-circle" plain round hairline size="small" type="primary"
                @click="startVideoRecord">录制</Button>
            </template>
          </Field>
          <div v-if="form.videoList !== undefined && form.videoList.length > 0">
            <div class="van-uploader" v-for="(videoUrl, index) in form.videoList" :key="index">
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="showVideo(videoUrl)" class="tag_margin">
                    <Tag plain size="large" type="danger">视频文件{{ index + 1 }}</Tag>
                  </div>
                  <div class="van-uploader__preview-delete" @click="delObj('video', videoUrl)">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <Field name="checkres" label="录制语音" size="large">
            <template #input>
              <Button class="mg5" plain round hairline icon="volume" size="small" type="warning" :loading="btnLoading"
                loading-text="正在播放" @touchstart.native="recordAudio" @touchend.native="stopRecordAudio">按住说话</Button>
            </template>
          </Field>
          <div v-if="form.audioList !== undefined && form.audioList.length > 0">
            <div class="van-uploader" v-for="(audioUrl, adIndex) in form.audioList" :key="adIndex">
              <div class="van-uploader__wrapper">
                <div class="van-uploader__preview">
                  <div @click="showAudio(audioUrl)" class="tag_margin">
                    <Tag plain size="large" type="success">语音文件{{ adIndex + 1 }}</Tag>
                  </div>
                  <div class="van-uploader__preview-delete" @click="delObj('audio', audioUrl)">
                    <i class="van-icon van-icon-cross van-uploader__preview-delete-icon"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <Button color="#ff9933" :block="true" class="buttonLeft" v-show="btnShow" type="primary" text="取消" @click="close" />
      <Button color="#1076c0" :block="true" class="buttonRight" v-show="btnShow" :hairline="false" type="primary"
        :disabled="subButton" text="保存" @click="save" />
    </div>
  </div>
</template>

<script>
import {
  Form,
  Cell,
  Icon,
  Field,
  NumberKeyboard,
  Image as VanImage,
  Picker,
  popup,
  SubmitBar,
  Divider,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
  NoticeBar,
  Row,
  Tag,
  ImagePreview,
  CellGroup,
  Uploader,
  Col,
} from "vant";
import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";
Vue.use(Overlay);
Vue.use(Loading);

Vue.use(Divider);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);

export default {
  name: "qualityInspection",
  components: {
    Button,
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    VTable,
    Dialog,
    Toast,
    NoticeBar,
    Row,
    Tag,
    ImagePreview,
    CellGroup,
    Uploader,
    Col,
  },
  data: function () {
    return {
      btnLoading: false,
      btnShow: true,
      subButton: true, //提交按钮默认状态
      sourceShowPicker: false,
      reasonTemp: null, //原因
      form: {
        user: null,
        type: "2", //生产1物流2质量3
        siteKey: null,
        eqKey: null,
        equipName: null, //设备编码
        equipDesc: null, //设备名称
        callUser: null, //呼叫人
        callTime: null, //呼叫时间
        remark: null,
        callReason: null, //呼叫原因
        picList: [],
        videoList: [],
        audioList: [],
      },
      columns: [],
      pickListMap: new Map(),
      user: {}, //登录用户信息
      uploadSuccess: false,
    };
  },
  //页面初始化监听事件
  created: function () {
    this.user = JSON.parse(storage.get("user"));
    this.form.siteKey = this.user.site;
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) { }
    );

    // try {
    //   var manageStorage = api.require('manageStorage');
    //   manageStorage.requestAllFilePermission({
    //   }, function (ret) {
    //     // api.alert({
    //     //   msg: JSON.stringify(ret)
    //     // })
    //   });
    // } catch {

    // }
    
  },
  //页面初始化完成监听事件
  mounted: function () {
    this.showScanner();
    this.getPickList();
    const oldHight = api.winHeight;
    addEventListener("resize", () => {
      let newHight = api.winHeight;
      this.btnShow = newHight < oldHight ? false : true;
    });
  },
  methods: {
    picShow(pIndex) {
      ImagePreview({
        images: this.form.picList || [],
        showIndicators: true,
        startPosition: pIndex || 0,
        showIndex: false,
      });
    },
    showCamera() {
      let that = this;
      //判断设备系统类型
      if (api.systemType == "ios") {
        that.iosCamera();
      } else {
        if (api.deviceName.toLowerCase() == "vivo") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "oppo") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "oneplus") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "honor") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "xiaomi") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "meizu") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "ptac") {
          that.vivoCamera();
        } else {
          // that.otherCamera();
          that.otherCameraPlus();
        }
        // var phoneInfo = api.require('phoneInfo')
        // phoneInfo.getBaseInfo(function(ret, err) {
        //   if (ret.status) {
        //     if (ret.brand == 'vivo') {
        //       // that.vivoCamera()
        //       that.iosCamera()
        //     } else if (ret.brand == 'oppo') {
        //       that.oppoReno2Camera()
        //     } else {
        //       that.otherCamera()
        //     }
        //   } else {
        //     api.alert({ msg: err.msg })
        //   }
        // })
      }
    },

    vivoCamera() {
      let that = this;
      var FNPhotograph = api.require("FNPhotograph");
      FNPhotograph.open(
        {
          album: false,
          quality: "high",
          isShowAlbum: false,
          // useAdvanceFeature: true,
          // pictureSize: '2075x1080',
          // previewSize: '2075x1080',
        },
        function (ret) {
          if (ret && ret.eventType == "takePhoto") {
            let imgSrc = ret.imagePath;
            if (imgSrc && imgSrc != "") {
              FNPhotograph.close();
              that.imageFilter(imgSrc);
            }
          }
        }
      );
    },

    oppoReno2Camera() {
      let _this = this;
      api.getPicture(
        {
          sourceType: "camera",
          encodingType: "jpg",
          mediaValue: "pic",
          allowEdit: false,
          destinationType: "url",
          quality: 50,
        },
        function (ret, err) {
          // 获取拍照数据并处理
          if (ret) {
            let imgSrc = ret.data;
            if (imgSrc && imgSrc != "") {
              _this.imageFilter(imgSrc);
            }
          }
        }
      );
    },

    otherCamera() {
      let that = this;
      // var cameraTool = api.require('cameraTool')
      // cameraTool.openCamera(function(ret, err) {
      //   let imgPath = ret.imgPath
      //   if (imgPath && imgPath != '') {
      //     that.imageFilter(imgPath)
      //   }
      // })
      var module = api.require("easyCamera");
      var param = {
        typeString: "image", // 或者'video-20'
      };
      var resultCallback = function (ret, err) {
        var msg = ret.msg;
        if (msg && msg != "") {
          that.imageFilter(msg);
        }
      };
      module.openCamera(param, resultCallback);
    },
    otherCameraPlus() {
      let that = this;
      var ox = api.require("oxWxRecorder");
      ox.getPermission(function (ret) {
        var code = ret.code;
        if (code == 1) {
          ox.open(
            {
              fixedOn: api.frameName,
              rect: { x: 0, y: 0, w: w, h: h },
              fixed: true,
              type: 2, //0拍照录像 1 录像 2 拍照
            },
            function (ret1) {
              var code1 = ret1.code;
              if (code1 == 0) {
                //关闭事件
              } else if (code1 == 2) {
                //返回图片路径path
                that.imageFilter(ret1.path);
              } else if (code1 == -1) {
                //错误信息
                alert(ret1.text);
              }
            }
          );
        }
      });
    },
    xiaomiCamera() {
      let that = this;
      var cameraTool = api.require("cameraTool");
      cameraTool.openCamera(function (ret, err) {
        let imgPath = ret.imgPath;
        if (imgPath && imgPath != "") {
          that.imageFilter(imgPath);
        }
      });
    },
    iosCamera() {
      let that = this;
      let zySmallVideo = api.require("zySmallVideo");
      zySmallVideo.openNew(
        {
          rect: {
            //模块 附于一个frame之上
            x: 0,
            y: 0,
            w: api.frameWidth,
            h: api.frameHeight,
          },
          fixedOn: api.frameName,
          fixed: true,
          videoInfo: {
            setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
            setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
            setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
          },
          MaxRecordTime: 60, //最大录制时间 单位秒 默认10
          MinRecordTime: 5, //最短录制时间  单位s
          MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
          setFeatures: 1001, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
          setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
          setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
          setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
          setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
          setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
          cameraInfo: {
            //摄像头 设置样式
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            margin_l: 0, //距左 默认都是0
            margin_r: 35, //距右
            margin_t: 65, //距上
            margin_b: 0, //距下
          },
          foucsInfo: {
            //点击的对焦框 样式
            color: "#cd0000", //线条颜色 默认16AE16
            width: 4, //线条宽度 默认4
          },
          recordInfo: {
            progress_color: "#cd0000", //进度条颜色 默认16AE16
            outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
            inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
          },
          confirmInfo: {
            //确认框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
          cancelInfo: {
            //取消框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.type == "captureSuccess") {
              that.imageFilter(ret.result);
            }
          }
        }
      );
    },

    //图片压缩
    imageFilter(imgPath) {
      let that = this;
      var imageFilter = api.require("imageFilter");
      var imageCachePath = api.cacheDir; //cache://协议对应的真实目录，字符串类型
      imageFilter.compress(
        {
          img: imgPath,
          quality: 0.5,
          size: "800X600",
          save: {
            album: false,
            imgPath: imageCachePath + "/",
            imgName: "cs.jpg",
          },
        },
        function (ret, err) {
          let imgUrl = imageCachePath + "/cs.jpg";
          that.getFileName("pic", imgUrl);
          //文件删除
          var fs = api.require("fs");
          fs.remove(
            {
              path: imgPath,
            },
            function (ret, err) {
              if (ret.status) {
              } else {
              }
            }
          );
        }
      );
    },
    recordAudio() {
      this.$ac.showProgress({
        title: "录制中...",
        text: "释放手指结束录音...",
        modal: false,
      });
      //开始录音
      this.$ac.startRecord({
        // path: 'fs://audio.amr',
        path: "fs://audio.aac",
        format: "aac",
      });
    },
    stopRecordAudio() {
      let that = this;
      that.$ac.hideProgress();
      that.$ac.stopRecord(function (ret, err) {
        if (ret) {
          that.getFileName("audio", ret.path);
        }
      });
    },
    showAudio(audioUrl) {
      let that = this;
      if (!audioUrl) {
        Toast("没有要播放的文件");
        return;
      }
      that.btnLoading = true;

      let audioStreamer = api.require("audioStreamer");
      let _this = this;
      audioStreamer.addEventListener({}, function (ret) {
        if (ret.state == "finished") {
          that.btnLoading = false;
        }
      });
      if (api.systemType == "ios") {
        api.download(
          {
            url: audioUrl,
          },
          function (res) {
            if (res.state == 1) {
              api.startPlay(
                {
                  path: res.savePath,
                },
                function (ret, err) {
                  if (ret) {
                    // _that.activeAudio = ''
                  } else {
                    alert(JSON.stringify(err));
                  }
                }
              );
            }
          }
        );
      } else {
        audioStreamer.openPlayer(
          {
            path: audioUrl,
          },
          function (ret) { }
        );
      }
    },
    startVideoRecord() {
      if (api.systemType == "ios") {
        let that = this;
        let zySmallVideo = api.require("zySmallVideo");
        zySmallVideo.openNew(
          {
            rect: {
              //模块 附于一个frame之上
              x: 0,
              y: 0,
              w: api.frameWidth,
              h: api.frameHeight,
            },
            fixedOn: api.frameName,
            fixed: true,
            videoInfo: {
              //视频高级设置 不懂请勿修改
              //videoSize_w:720,//视频分辨率 宽 默认720
              //videoSize_h:1280,//视频分辨率 高 默认1280
              setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
              setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
              setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
            },
            MaxRecordTime: 60, //最大录制时间 单位秒 默认10
            MinRecordTime: 5, //最短录制时间  单位s
            MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
            setFeatures: 1002, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
            setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
            setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
            setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
            setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
            setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
            cameraInfo: {
              //摄像头 设置样式
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              //w:120,// 摄像头宽度 默认 120
              //h:92,// 摄像头高度 默认 92
              margin_l: 0, //距左 默认都是0
              margin_r: 35, //距右
              margin_t: 65, //距上
              margin_b: 0, //距下
            },
            foucsInfo: {
              //点击的对焦框 样式
              color: "#cd0000", //线条颜色 默认16AE16
              width: 4, //线条宽度 默认4
            },
            recordInfo: {
              //录制时的参数
              //button_radius:120,//外圆半径 默认120
              //button_inside_radius:90,//内圆半径 默认90
              progress_color: "#cd0000", //进度条颜色 默认16AE16
              outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
              inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
              //strokeWidth:15,//进度条宽度 默认15
              //outside_add_size:48,//长按外圆半径变大的Size 默认48
              //inside_reduce_size:30,//长按内圆缩小的Size 默认30
            },
            confirmInfo: {
              //确认框参数
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              img: "", //设置自定义图片
              //w:220,//宽 默认200
              //h:220,//高 默认200
              //margin_r:170, //确认按距右
            },
            cancelInfo: {
              //取消框参数
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              img: "", //设置自定义图片
              //w:220,//宽 默认200
              //h:220,//高 默认200
              //margin_l:170,//确认按距左
            },
          },
          function (ret, err) {
            if (ret.status) {
              // fileUrl = ret.fileUrl
              // document.getElementById('videoPic').src = ret.result
              if (ret.type == "recordSuccess") {
                that.getFileName("video", ret.url);
              }
            }
          }
        );
      } else {
        let that = this;
        let zySmallVideo = that.$ac.require("zySmallVideo");
        zySmallVideo.open(
          {
            MaxRecordTime: 60,
            MinRecordTime: 6, //最短录制时间  单位s
            MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
            videoColor: api.systemType == "ios" ? 0xcd0000 : "#cd0000",
            AVAssetExportPreset: "AVAssetExportPreset1280x720",
            mVideoSizeW: 720,
            mVideoSizeH: 1280,
          },
          function (ret, err) {
            if (ret.result == "success") {
              that.getFileName("video", ret.fileUrl);
            }
          }
        );
      }
    },
    showVideo(videoUrl) {
      let that = this;
      if (!videoUrl) {
        Toast("请先录制视频");
        return;
      }
      that.$ac.openVideo({
        url: videoUrl,
      });
    },

    // async putObj(fType, fUrl) {
    //   let _this = this
    //   Toast.loading({
    //     mask: true,
    //     forbidClick: true,
    //     duration: 0,
    //     message: '请稍等...',
    //   })
    //   try {
    //     let res = await _httpClient.postFile(_httpClient.getApiPrefix() + '/minio/oss/putObject', {
    //       files: {
    //         file: fUrl,
    //       },
    //     })
    //     if (res.code === 200) {
    //       if (res.fileUrl) {
    //         Toast.clear()
    //         if (fType === 'audio') {
    //           _this.form.audioList.push(res.fileUrl)
    //         } else if (fType === 'video') {
    //           _this.form.videoList.push(res.fileUrl)
    //         } else if (fType === 'pic') {
    //           _this.form.picList.push(res.fileUrl)
    //         }
    //       }
    //     }
    //   } catch (e) {
    //     Toast.fail(JSON.stringify(e))
    //   }
    // },

    //获取文件名称
    async getFileName(fType, fUrl) {
      let type = "jpg";
      if (fType === "audio") {
        type = "amr";
      } else if (fType === "video") {
        type = "mp4";
      } else if (fType === "pic") {
        type = "jpg";
      } else if (fType === "audio2") {
        type = "aac";
      }
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/getFileName?fileType=" + type
      );
      if (res.code === 200) {
        //上传文件
        this.putObj(fType, fUrl, res.fileName);
      }
    },

    //定时器
    timeCycle(fType, fileName) {
      let that = this;
      let cycleNum = 0;
      that.uploadSuccess = false;
      let intervald = setInterval(() => {
        if (
          that &&
          !that._isDestroyed &&
          cycleNum < _httpClient.getUploadCycle() &&
          !that.uploadSuccess
        ) {
          setTimeout(() => {
            if (that && !that._isDestroyed) {
              that.queryFileUpload(fType, fileName);
              cycleNum++;
            }
          }, 0);
        } else {
          //清除定时器
          clearInterval(intervald);
          that.uploadSuccess = true;
          Toast.clear();
          if (cycleNum == _httpClient.getUploadCycle()) {
            alert("上传超时，请重试");
          }
        }
      }, 2000);
    },

    //查询文件是否上传成功
    async queryFileUpload(fType, fileName) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "校验保存中...",
      });
      let that = this;
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/" + fileName
      );
      if (res.code === 200) {
        let urls = res.objectURL.split("?");
        if (urls.length > 0) {
          if (fType === "audio") {
            that.form.audioList.push(urls[0]);
          } else if (fType === "video") {
            that.form.videoList.push(urls[0]);
          } else if (fType === "pic") {
            that.form.picList.push(urls[0]);
          } else if (fType === "audio2") {
            that.form.audioList.push(urls[0]);
          }
          Toast("上传成功");
        }
        Toast.clear();
        that.uploadSuccess = true;
      }
    },

    //文件上传
    putObj(fType, fUrl, fileName) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "上传中...0%",
      });
      api.ajax(
        {
          url:
            _httpClient.getApiPrefix() +
            "/minio/oss/appPutObject?fileName=" +
            fileName,
          //  url: 'http://192.168.2.102:8083' + '/minio/oss/putObject',
          method: "post",
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          report: true,
          data: {
            files: {
              file: fUrl,
            },
          },
        },
        function (ret, err) {
          if (ret) {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 0,
              message: "上传进度...\n" + ret.progress + "%",
            });
            if (ret.body.code === 200) {
              if (api.systemType == "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            } else if (ret.progress == 100) {
              _this.timeCycle(fType, fileName);
              //文件删除
              var fs = api.require("fs");
              fs.remove(
                {
                  path: fUrl,
                },
                function (ret, err) {
                  if (ret.status) {
                  } else {
                  }
                }
              );
            }
          } else {
            Toast.clear();
          }
        }
      );
    },

    async delObj(fType, fUrl) {
      this.btnLoading = false;
      let fname = "";
      try {
        if (fUrl != undefined && fUrl != "" && fUrl != null) {
          fname = fUrl.substring(fUrl.lastIndexOf("/") + 1);
        }
        let res = await _httpClient.delete(
          _httpClient.getApiPrefix() + "/minio/oss/" + fname
        );
        if (res.code === 200) {
          let flist = [];
          if (fType === "audio") {
            flist = this.form.audioList;
          } else if (fType === "video") {
            flist = this.form.videoList;
          } else if (fType === "pic") {
            flist = this.form.picList;
          }
          if (flist.length > 0) {
            for (var i = 0; i < flist.length; i++) {
              if (flist[i] == fUrl) {
                flist.splice(i, 1);
              }
            }
          }
          Toast.success(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    //打开扫描
    showScanner() {
      let _this = this;
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {
        // _this.form.equipName = ret.result;
        //       _this.afterScan();

        var zyHmsScan = api.require('zyHmsScan');
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          //_this.addBarCode(ret.result);
          _this.form.equipName = ret.result;
          _this.afterScan();
          //api.alert({ msg: JSON.stringify(ret) });
        });
        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 15, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //       _this.form.equipName = ret.result;
        //       _this.afterScan();
        //     }
        //   }
        // );
        //       QRScan.closeCustomizedScanner();
      } else {
        var FNScanner = this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                _this.form.equipName = ret.content;
                _this.afterScan();
              }
            } else {
              alert(JSON.stringify(err));
            }
          }
        );
      }
    },
    //扫描流转单号后查询相关信息
    async afterScan() {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          "/app/resourcecall/resourceCallInfo/equipDesc",
          {
            body: {
              equipName: _this.form.equipName,
              siteKey: _this.form.siteKey,
            },
          }
        );
        if (res.code === 200) {
          _this.form.eqKey = res.rows[0].eqKey;
          _this.form.equipDesc = res.rows[0].equipDesc;
          _this.form.user = _this.user.nickName;
          _this.form.callUser = _this.user.userName;
          _this.form.callTime = _this.getNowTime();
          if (_this.form.callReason) {
            _this.subButton = false;
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //获取下拉框数据
    async getPickList() {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          "/app/resourcecall/resourceCallInfo/listFault",
          {
            body: _this.form,
          }
        );
        if (res.code === 200) {
          //将数据放到MAP当中去
          for (let i = 0; i < res.rows.length; i++) {
            _this.columns.push(res.rows[i].faultDesc);
            _this.pickListMap.set(res.rows[i].faultDesc, res.rows[i].faultDesc);
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //保存
    async save() {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "保存中...",
      });
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          "/app/resourcecall/resourceCallInfo/save",
          {
            body: _this.form,
          }
        );
        if (res.code === 200) {
          Toast.success(res.msg);
          _this.reset();
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    getNowTime() {
      let today = new Date();
      let month = today.getMonth() + 1;
      month = month < 10 ? "0" + month : month;
      let day = today.getDate() < 10 ? "0" + today.getDate() : today.getDate();
      let hours =
        today.getHours() < 10 ? "0" + today.getHours() : today.getHours();
      let mins =
        today.getMinutes() < 10 ? "0" + today.getMinutes() : today.getMinutes();
      let secs =
        today.getSeconds() < 10 ? "0" + today.getSeconds() : today.getSeconds();
      return (
        today.getFullYear() +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        mins +
        ":" +
        secs
      );
    },

    //下拉框确认确认
    sourceOnConfirm(value) {
      this.sourceShowPicker = false;
      if (value === undefined) {
        return;
      }
      this.form.callReason = value;
      if (this.form.equipDesc) {
        this.subButton = false;
      }
    },
    close() {
      api.closeWin();
    },
    reset() {
      this.subButton = true;
      this.form.equipDesc = null;
      this.form.equipName = null;
      this.form.eqKey = null;
      this.form.callUser = null;
      this.form.callTime = null;
      this.form.remark = null;
      this.form.callReason = null;
      this.form.user = null;
      this.form.picList = [];
      this.form.videoList = [];
      this.form.audioList = [];
    },
  },
};
</script>
<style>
body {
  background-color: white;
}

.table-title-class {
  background-color: #304156;
  color: #fff;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.buttonLeft {
  position: fixed;
  bottom: 8px;
  float: left;
  width: 49%;
}

.buttonRight {
  position: fixed;
  bottom: 8px;
  float: right;
  left: 51%;
  width: 49%;
  background-color: #f22028;
  border-color: #f22028;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 4rem;
  bottom: 5rem;
  overflow: scroll;
  right: 0;
  width: 100%;
  z-index: 1;
}

.message {
  font-size: 15px;
  margin-top: 5px;
  margin-left: -10px;
  font-weight: bold;
}

.mg5 {
  margin-right: 5px;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 100%;
  width: 100%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}
</style>
